-module(quek_utf16_utf8).
-export([conv/1]).

conv(Utf16) when Utf16 < 16#0080 ->
    Utf16;
conv(Utf16) when Utf16 < 16#0800 ->
    <<U, L>> = <<Utf16:16/big>>,
    X = (U bsl 2) bor ((L band 2#11000000) bsr 6),
    Y = L band 2#00111111,
    <<Utf8:16/big>> = <<(2#11000000 bor X), (2#10000000 bor Y)>>,
    Utf8;
conv(Utf16) when Utf16 < 16#10000 ->
    <<U, L>> = <<Utf16:16/big>>,
    X = (U band 2#11110000) bsr 4,
    Y = ((U band 2#00001111) bsl 2) bor ((L band 2#11000000) bsr 6),
    Z = L band 2#00111111,
    ((2#11100000 bor X) bsl 16) bor
	((2#10000000 bor Y) bsl 8) bor
	(2#10000000 bor Z);
conv(Utf16) when Utf16 < 16#20000 ->
    <<_, B, C, D>> = <<Utf16:32/big>>,
    W = (B band 2#00011100) bsr 2,
    X = ((B band 2#00000011) bsl 4) bor ((C band 2#11110000) bsr 4),
    Y = ((C band 2#00001111) bsl 2) bor ((D band 2#11000000) bsr 6),
    Z = D band 2#00111111,
    <<Utf8:32/big>> = <<(W bor 2#11110),
		       (X bor 2#10000000),
		       (Y bor 2#10000000),
		       (Z bor 2#10000000)>>,
    Utf8.
